<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between">
        <div class="flex_start">
          <div class="wp400" style="display: flex; gap: 12px;">
            <el-input v-model="params.username" class="pub_input pub_input_search" placeholder="邀请人账号" clearable @keydown.enter.native="handleSearch" @clear="handleSearch">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
            <el-input v-model="params.wechatNo" class="pub_input pub_input_search" placeholder="发放奖励微信号" clearable @keydown.enter.native="handleSearch" @clear="handleSearch">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
          </div>
          <div class="table_filter_search ml12 w150">
            <el-radio-group v-model="params.isGrant" size="small" @change="handleSearch">
              <el-radio-button label="2">未发放</el-radio-button>
              <el-radio-button label="1">已发放</el-radio-button>
            </el-radio-group>
          </div>
          <div class="table_filter_search ml12 flex_start">
            <el-button type="text" size="small" class="public_confirm_btn pub_button" @click="handleSearch">搜索</el-button>
          </div>
        </div>
        <div class="greenBox flex_start">
          <span class="mr8" style="line-height: 32px; color: #333;">红包功能：</span>
          <el-radio-group v-model="rewardStatus" size="small" @change="handleRewardStatusChange">
            <el-radio-button label="1">开启</el-radio-button>
            <el-radio-button label="2">关闭</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <!-- 表格区域 -->
      <div ref="pubTableRef">
        <el-table ref="multipleTable" size="mini" :data="tableData" tooltip-effect="dark" border :height="tableHeight" class="wp100 mt12" @selection-change="handleSelectionChange">
          <el-table-column prop="username" label="邀请人账号" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="invitedUsername" label="受邀人账号" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="awardReason" label="奖励原因" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="awardAmount" label="奖励数额" min-width="80" align="center" />
          <el-table-column prop="awardTime" label="发生时间" min-width="180" align="center" />
          <el-table-column prop="isGrant" label="是否已发放奖励" min-width="120" align="center">
            <template slot-scope="scope">
              <span :class="scope.row.isGrant === '1' ? 'cGR' : 'cRD'">
                {{ scope.row.isGrant === '1' ? '已发放' : '未发放' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="screenshotUrl" label="转账截图" min-width="100" align="center">
            <template slot-scope="scope">
              <el-image v-if="scope.row.screenshotUrl" :src="scope.row.screenshotUrl" style="width: 40px; height: 40px;" :preview-src-list="[scope.row.screenshotUrl]" fit="cover"> </el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="wechatNo" label="发放奖励微信号" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="grantTime" label="发放奖励时间" min-width="180" align="center" />
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isGrant === '2'" type="text" class="pub_button public_1EB398_btn" size="mini" @click="handleEdit(scope.row)">
                发放奖励
              </el-button>
              <el-button v-if="scope.row.isGrant === '1'" type="text" style="color: #E53E3E" size="mini" @click="handleCancelGrant(scope.row)">
                取消发放
              </el-button>
            </template>
          </el-table-column>
          <template slot="empty">
            <PageEmptyData />
          </template>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div ref="pubPageinationRef" class="pub_pageination flex_center mt18">
        <el-pagination background :page-size="params.pageSize" :current-page.sync="params.pageNum" layout="total,prev, pager, next,sizes" :total="params.total" @current-change="changePage" @size-change="changeSize" />
      </div>
    </div>
    <!-- 编辑弹框 - 使用PageDialog组件 -->
    <PageDialog title="发放奖励" :dialog-visible="editDialogVisible" :width="`${$f * 500}px`" @close="closeDialog" @submit="handleSubmitEdit">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="转账截图" prop="screenshotUrl" required>
          <el-upload ref="upload" class="upload-demo" :action="uploadFileUrl" :headers="headers" :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload" :show-file-list="false" accept="image/*" :file-list="fileList" :on-change="changeUploadFile" :on-remove="handleRemoveFile">
            <img v-if="imageUrl" :src="imageUrl" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="微信号" prop="wechatNo" required>
          <el-input v-model="editForm.wechatNo" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="转账时间" prop="grantTime" required>
          <el-date-picker v-model="editForm.grantTime" type="datetime" placeholder="选择转账时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"> </el-date-picker>
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
import PageDialog from '@/components/PageDialog/index.vue';
export default {
  name: 'RedPacketConfig',
  components: {
    PageDialog
  },
  mixins: [tableFun],
  data() {
    return {
      params: {
        total: 0, // 总条数
        pageSize: 20, // 每页条数
        pageNum: 1, // 当前页码
        username: '', // 邀请人账号搜索
        wechatNo: '', // 发放奖励微信号搜索
        isGrant: '2' // 发放状态筛选
      },
      rewardStatus: '2', // 红包功能状态 '1'-开启 '2'-关闭
      // 编辑弹框相关
      editDialogVisible: false,
      editForm: {
        id: '',
        screenshotUrl: '',
        wechatNo: '',
        grantTime: ''
      },
      editRules: {
        screenshotUrl: [{ required: true, message: '请上传转账截图', trigger: 'blur' }],
        wechatNo: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
        grantTime: [{ required: true, message: '请选择转账时间', trigger: 'change' }]
      },
      // 上传相关
      imageUrl: '',
      // 导入上传文件的参数
      fileName: '', //文件名称
      fileList: [], //导入的文件
      isSelectedFile: false, //是否选中文件
      fileSizeMB: 0, //上传的文件尺寸
      uploadFileUrl: '' // 上传地址
    };
  },
  computed: {
    headers() {
      return {
        Authorization: this.$store.state.token || localStorage.getItem('token') || ''
      };
    }
  },
  async mounted() {
    await this.getRewardStatus();
    // 只有在红包功能开启时才请求数据
    if (this.rewardStatus === '1') {
      this.getDataList();
    }
    this.initUpload();
    this.calculateTableHeight();
  },
  methods: {
    // 覆盖mixin中的calculateTableHeight方法，避免getComputedStyle错误
    calculateTableHeight() {
      this.$nextTick(() => {
        // 简单设置表格高度，避免依赖this.$rules
        this.tableHeight = 600;
      });
    },
    // 关闭弹框
    closeDialog() {
      this.editDialogVisible = false;
      // 重置表单
      if (this.$refs.editForm) {
        this.$refs.editForm.resetFields();
      }
      this.imageUrl = '';
      this.handleRemoveFile();
    },
    // 获取列表数据
    async getDataList() {
      // 只有在红包功能开启时才请求数据
      if (this.rewardStatus === '1') {
        const response = await this.$api.get(this.$url.adminRewardList, { ...this.params });
        this.tableData = response.rows || [];
        this.params.total = response.total || 0;
      } else {
        // 关闭时清空表格数据
        this.tableData = [];
        this.params.total = 0;
      }
    },
    // 初始化上传配置
    initUpload() {
      this.uploadFileUrl = this.$url.development + this.$url.publicUrl + this.$url.uploadScreenshot;
    },
    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 文件状态改变触发此方法
    changeUploadFile(file, fileList) {
      this.fileList = fileList;
      const fileSize = file.size; // 单位：字节 (Bytes)
      const fileSizeKB = Math.round(fileSize / 1024); // 转 KB
      const fileSizeMB = (fileSizeKB / 1024).toFixed(2); // 转 MB
      this.fileSizeMB = fileSizeMB;
      this.fileName = file.name;
      this.isSelectedFile = true;
    },
    // 删除文件时触发此方法
    handleRemoveFile() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.fileList = [];
      this.isSelectedFile = false;
    },
    // 上传成功回调
    handleUploadSuccess(response, file) {
      if (response.code === 200 && response.data) {
        this.editForm.screenshotUrl = response.data.url;
        this.imageUrl = response.data.url;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error('图片上传失败');
      }
    },
    // 上传失败回调
    handleUploadError(err, file) {
      console.error('上传失败:', err);
      this.$message.error('图片上传失败');
    },
    // 获取红包功能状态
    async getRewardStatus() {
      try {
        const response = await this.$api.get(this.$url.queryReward);
        if (response.data && response.data.settingValue) {
          this.rewardStatus = response.data.settingValue;
        }
      } catch (error) {
        console.error('获取红包功能状态失败:', error);
      }
    },
    // 红包功能状态变化处理
    async handleRewardStatusChange(value) {
      try {
        const params = {
          settingKey: 'PROMOTION_REWARD',
          settingValue: value
        };
        await this.$api.post(this.$url.saveReward, params);
        this.$message.success('红包功能状态更新成功');
        // 根据新状态处理表格数据
        if (value === '2') {
          // 切换为关闭时清空表格数据
          this.tableData = [];
          this.params.total = 0;
        } else if (value === '1') {
          // 切换为开启时重新请求数据
          this.getDataList();
        }
      } catch (error) {
        console.error('更新红包功能状态失败:', error);
        this.$message.error('更新红包功能状态失败');
        // 恢复原状态
        this.rewardStatus = this.rewardStatus === '1' ? '2' : '1';
      }
    },
    // 搜索处理
    handleSearch() {
      this.params.pageNum = 1;
      this.getDataList();
    },
    // 处理编辑
    handleEdit(row) {
      this.editDialogVisible = true;
      this.editForm = {
        id: row.id,
        screenshotUrl: row.screenshotUrl || '',
        wechatNo: row.wechatNo || '',
        grantTime: row.grantTime || ''
      };
      this.imageUrl = row.screenshotUrl || '';
      this.handleRemoveFile();
    },
    // 处理删除
    handleDelete(row) {
      // 实现删除逻辑
    },
    // 处理取消发放
    async handleCancelGrant(row) {
      try {
        await this.$confirm('确定要取消发放该奖励吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await this.$api.post(this.$url.cancelGrant, { id: row.id });
        this.$message.success('取消发放成功');
        this.getDataList();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消发放失败:', error);
          this.$message.error('取消发放失败');
        }
      }
    },
    // 提交编辑表单
    async handleSubmitEdit() {
      try {
        await this.$refs.editForm.validate();
        const params = {
          id: this.editForm.id,
          screenshotUrl: this.editForm.screenshotUrl,
          wechatNo: this.editForm.wechatNo,
          grantTime: this.editForm.grantTime
        };
        await this.$api.post(this.$url.grantReward, params);
        this.$message.success('发放奖励成功');
        this.editDialogVisible = false;
        this.getDataList();
      } catch (error) {
        console.error('发放奖励失败:', error);
        this.$message.error('发放奖励失败');
      }
    }
  }
};
</script>
<style lang="less" scoped>
.redPacketConfig {
  width: 100%;
  overflow: hidden;
  .table_content,
  .echarts {
    background: #ffffff;
    border-radius: 16px 16px 16px 16px;
    padding: 20px;
    box-sizing: border-box;
  }
  .table_content {
    width: 100%;
  }
  .table_filter_search {
    width: 200px;
  }
}
/* 状态颜色定义 */
.cGR {
  color: #1eb398;
}
.cRD {
  color: #f44336;
}
/* 上传组件样式 */
.upload-demo {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
  width: 100px;
  height: 100px;
  text-align: center;
  overflow: hidden;
  &:hover {
    border-color: #1eb398;
  }
  img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
</style>
